﻿using EdgeSearch.Application.Manager.LogManager.DTOS;
using EdgeSearch.Core.Entity.LogDB;
using EdgeSearch.Core.Entity.Models;
using EdgeSearch.Core.SqlSugar;
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Profiling.Internal;

namespace EdgeSearch.Application.Manager.LogManager
{
    public class DatabaseLoggingManager : ISingleton
    {
        private readonly IServiceProvider _services;
        private List<LogInfo> _logInfos;
        private int _batchSize;
        private int _projectId;
        public DatabaseLoggingManager(IServiceProvider serviceProvider)
        {
            _logInfos = new List<LogInfo>();
            _batchSize = int.Parse(App.Configuration["Logging:DataBase:BatchSize"]);
            _projectId = int.Parse(App.Configuration["Logging:DataBase:ProjectID"]);
            _services = serviceProvider;
        }

        /// <summary>
        /// 写到错误日志系统中
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public void AddDBLog(LogInfo log)
        {
            _logInfos.Add(log);
            if (_logInfos.Count >= _batchSize)
            {
                using var scope = _services.CreateScope();
                var _log = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<LogInfo>>();
                _log.InsertRange(_logInfos);
                _logInfos.Clear();
            }
        }

        /// <summary>
        /// 强制提交当前缓冲区的日志
        /// </summary>
        public async Task<int> SubmitBufferLogAsync()
        {
            using var scope = _services.CreateScope();
            var _log = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<LogInfo>>();
            var cmd = await _log.AsUpdateable(_logInfos).ExecuteCommandAsync();
            _logInfos.Clear();
            return cmd;
        }


        /// <summary>
        /// 获取存在缓冲区的日志
        /// </summary>
        /// <returns></returns>
        public List<LogInfo> GetBufferLogs()
        {
            return _logInfos;
        }


        /// <summary>
        /// 获取日志分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<WebPageRespon<List<LogInfo>>> GetLogListAsync(SearchLogInputDto input)
        {
            var result = new WebPageRespon<List<LogInfo>>();
            using var scope = _services.CreateScope();
            var logRep = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<LogInfo>>();


            PageModel PM = input.Adapt<PageModel>();
            //用于接收异步的Ref参数（out和ref不支持异步），将值引用类型包装成对象引用，用于接收totalNumber
            var totalNumber = new RefAsync<int>(0);
            //Querable的写法
            var list = await logRep.AsQueryable()
                .WhereIF(input.PID > 0, s => s.ProjectID == input.PID)
                .WhereIF(input.PID == 0, s => s.ProjectID == _projectId)
                .WhereIF(input.UID > 0, s => s.UserID == input.UID)
                .WhereIF(!string.IsNullOrWhiteSpace(input.StartTime.ToString()), s => s.CreateDate >= input.StartTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.EndTime.ToString()), s => s.CreateDate <= input.EndTime)
                .OrderBy(s => s.CreateDate, OrderByType.Desc)
                .ToPageListAsync(PM.PageIndex, PM.PageSize, totalNumber);
            PM.TotalCount = totalNumber;
            //仓储封装了一些常用的数据操作方法
            //list = await logRep.GetPageListAsync(it=>it.ProjectID==_projectId ,page,it=>it.CreateDate,OrderByType.Desc);
            result.PM = PM;
            result.Data = list;
            return result;
        }

    }
}
